﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fly.Common.Linq;
using Newtonsoft.Json;

namespace RN.ERP.Web.Person
{
    public partial class PersonEmpSearch : BasePage
    {
        public override bool IsCheckPermission
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 登录用户roleid
        /// </summary>
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }
        /// <summary>
        /// 当前市场
        /// </summary>
        protected string AreaCode
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initial();
                BindFlowCode();
            }
        }
        /// <summary>
        /// 取得参数
        /// </summary>
        private void Initial()
        {
            int classId=0;
            ////人员类型
            if (Request.QueryString["classId"] != null)
            {
                int.TryParse(Request.QueryString["classId"], out classId);
            }
            ////企业guid
            if (Request.QueryString["corpGuid"] != null)
            {
                hdCorpGuid.Value = Request.QueryString["corpGuid"];
            }
            ////当前地区
            if (Request.QueryString["areaCode"] != null)
            {
                hdAreaCode.Value = Request.QueryString["areaCode"];
            }
            ////用户角色类型
            if (Request.QueryString["roleType"] != null)
            {
                hdRoleType.Value = Request.QueryString["roleType"];
            }
            if (Request.QueryString["roleId"] != null)
            {
                hdRoleId.Value = Request.QueryString["roleId"];
            }
            ////证书类型
            if (Request.QueryString["itemType"] != null)
            {
                hdEmpItemType.Value=Request.QueryString["itemType"].Trim();
            }
            if (Request.QueryString["ItemFlag"] != null)
            {
                hdEmpItemFlag.Value = Request.QueryString["ItemFlag"].Trim();
            }
            //外地人员标识
            if (!string.IsNullOrEmpty(Request.QueryString["other"]))
            {
                hdOtherAreaCode.Value = Request.QueryString["other"].Trim();
            }
            //地区号
            if (Request.QueryString["a"] != null)
            {
                hdEmpAreaCode.Value = Request.QueryString["a"].Trim();
            }
            //标识在管理端通过企业guid查询列表
            if (Request.QueryString["tag"] != null)
            {
                hdTag.Value = Request.QueryString["tag"].Trim();
            }
            hdClassId.Value = classId.ToString();
            GetSex();
        }
        /// <summary>
        /// 加载审核状态
        /// </summary>
        private void BindFlowCode()
        {
            if (SystemID.Equals("97") || SystemID.Equals("101"))
            {
                BindFlowCodeForYTLC();
                return;
            }
            string classId = hdClassId.Value;
            if (string.IsNullOrEmpty(classId) || classId == "0")
            {
                classId = "2511";
            }
            var dic = UtilitiesTool.GetAllFlowStatus(classId, hdAreaCode.Value, hdRoleId.Value);
            dropEmpStatus.DataSource = dic;
            dropEmpStatus.DataTextField = "key";
            dropEmpStatus.DataValueField = "value";
            dropEmpStatus.DataBind();

        }
        private void BindFlowCodeForYTLC()
        {
            string msg = string.Empty;
            string classId = hdClassId.Value;
            if (string.IsNullOrEmpty(classId) || classId == "0")
            {
                classId = "2511";
            }

            Dictionary<string, string> list = new Dictionary<string, string>();
            Dictionary<string, string> listNew = new Dictionary<string, string>();
            BasicService.BasicServiceClient client = new BasicService.BasicServiceClient();
            list = JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetAllBusinessStatusAndProcessing(out msg, RoleId, AreaCode, classId, false));

            foreach (var item in list.Keys)
            {
                if (item.Equals("0"))
                {
                    continue;////主管端不显示未上报的
                }
                string key = item;
                if (key.Contains("@"))
                {
                    key = key.Replace('@', '|');

                }
                listNew.Add(key, list[item]);
            }

            dropEmpStatus.DataTextField = "Value";
            dropEmpStatus.DataValueField = "Key";
            dropEmpStatus.DataSource = listNew;
            dropEmpStatus.DataBind();

            if (listNew != null && listNew.Count > 1)
            {
                dropEmpStatus.SelectedIndex = 1;
            }
        }

        /// <summary>
        /// 取得字典数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetGetDictionary(string type, string condition)
        {
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetDictionary(type, condition, hdAreaCode.Value));
            }
        }
        /// <summary>
        /// 取得性别绑定下拉列表框
        /// </summary>
        private void GetSex()
        {
            ////性别
            DropSex.DataSource = GetGetDictionary("empsex", "");
            DropSex.DataTextField = "value";
            DropSex.DataValueField = "key";
            DropSex.DataBind();
            DropSex.Items.Insert(0,new ListItem("请选择",""));

        }
        /// <summary>
        /// 取得客户端选择的条件生成参数列表
        /// </summary>
        /// <returns></returns>
        private List<Dictionary<string, string>> GetQueryParam()
        {
            if (string.IsNullOrEmpty(hdSearchStr.Value.Trim()))
            {
                return null;
            }
            string[] keyArry;
            string[] arry = hdSearchStr.Value.Trim().Split('&');
            Dictionary<string, string> dict = new Dictionary<string, string>();
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            string flowCode = string.Empty;
            //审核状态之外的参数
            foreach (string a in arry)
            {
                if (string.IsNullOrEmpty(a) || a.IndexOf("=") <= 0)
                {
                    continue;
                }
                if (a.IndexOf("|") > 0)
                {
                    flowCode = a;
                }
                else
                {
                    keyArry = a.Split('=');
                    if (!string.IsNullOrEmpty(keyArry[1]) && keyArry[1]!="-1")
                    {
                        dict.Add(keyArry[0], keyArry[1].Trim());
                    }
                }
            }
            //增加审核状态参数
            if (!string.IsNullOrEmpty(flowCode))
            {
                keyArry = flowCode.Split('=');
                string[] codes = keyArry[1].Split('|');
                foreach (string code in codes)
                {
                    if (string.IsNullOrEmpty(code))
                    {
                        continue;
                    }
                    Dictionary<string, string> dict1 = new Dictionary<string, string>();
                    dict1.Add(keyArry[0], code);
                    foreach (KeyValuePair<string, string> a in dict)
                    {
                        dict1.Add(a.Key, a.Value.Trim());
                    }
                    list.Add(dict1);
                }
            }
            else
            {
                list.Add(dict);
            }
          
            return list;
        }
        /// <summary>
        /// 取得查询条件列表
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions()
        {
            List<ModelService.QueryPersonInfoCondition> query = new List<ModelService.QueryPersonInfoCondition>();
            List<Dictionary<string, string>> queryList = GetQueryParam();
            if (queryList != null && queryList.Count > 0)
            {
                foreach (Dictionary<string, string> dict in queryList)
                {
                    ModelService.QueryPersonInfoCondition queryCondition = GetQueryCondition(dict);
                    query.Add(queryCondition);
                }
            }
            return JsonConvert.SerializeObject(query);
        }
        
        /// <summary>
        /// 组合参数列表生成查询条件
        /// </summary>
        /// <param name="flowCode"></param>
        /// <returns></returns>
        private ModelService.QueryPersonInfoCondition GetQueryCondition(Dictionary<string, string> dict)
        {
            ///设置查询参数
            ModelService.QueryPersonInfoCondition queryCondition = new ModelService.QueryPersonInfoCondition();
            queryCondition.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
            int classId = 0;
            int.TryParse(hdClassId.Value, out classId);
            if (classId > 0)
            {
                queryCondition.ClassId = new ParameterValue<int?> { V = classId, O = OptEnum.Equal };
            }
            ///用户端登陆
            if (hdRoleType.Value == "User" || hdTag.Value=="1")
            {
                Guid userGuid = Guid.Empty;
                Guid.TryParse(hdCorpGuid.Value, out userGuid);
                queryCondition.CorpGuid = new ParameterValue<Guid> { V = userGuid, O = OptEnum.Equal };
            }
            if (dict.ContainsKey("Name"))
            {
                queryCondition.Name = new ParameterValue<string> { V = dict["Name"], O = OptEnum.Like };
            }
            if (dict.ContainsKey("IDCard"))
            {
                queryCondition.IDCard = new ParameterValue<string> { V = dict["IDCard"], O = OptEnum.Equal };
            }
            if (dict.ContainsKey("Sex"))
            {
                queryCondition.Sex = new ParameterValue<byte?> { V = byte.Parse(dict["Sex"]), O = OptEnum.Equal };
            }
           
            if (dict.ContainsKey("CertificateSpecialty"))
            {
                queryCondition.CertificateSpecialty = new ParameterValue<string> { V = dict["CertificateSpecialty"], O = OptEnum.Equal };
            }
            if (dict.ContainsKey("CertificateLevel"))
            {
                queryCondition.CertificateLevel = new ParameterValue<string> { V = dict["CertificateLevel"], O = OptEnum.Equal };
            }
            if (dict.ContainsKey("corpName"))
            {
                queryCondition.corpName = new ParameterValue<string> { V = dict["corpName"], O = OptEnum.Like };
            }
            if (dict.ContainsKey("Post_psZG"))
            {
                queryCondition.Post_psZG = new ParameterValue<string> { V = dict["Post_psZG"], O = OptEnum.Equal };
            }
            if (dict.ContainsKey("Post_psZGCode"))
            {
                queryCondition.Post_psZGCode = new ParameterValue<string> { V = dict["Post_psZGCode"], O = OptEnum.Equal };
            }
            if (dict.ContainsKey("FlowCode"))
            {
                queryCondition.FlowCode = new ParameterValue<string> { V = dict["FlowCode"], O = OptEnum.Equal };
            }
            else
            {
                queryCondition.FlowCode = new ParameterValue<string> { V = "019", O = OptEnum.Like };
            }
            //证书类型
            if (GetTypeFlags(dict) != null && GetTypeFlags(dict).Values.Count>0)
            {
                queryCondition.TypeFlags = GetTypeFlags(dict);
            }
            /////地区查询
            if (!string.IsNullOrEmpty(hdEmpAreaCode.Value) && hdTag.Value=="0")
            {
                if (hdOtherAreaCode.Value.Length > 2)//本地
                {
                    queryCondition.AreaCode = new ParameterValue<string> { V = hdOtherAreaCode.Value, O = OptEnum.StartWith };
                }
            }
            return queryCondition;
        }
        /// <summary>
        /// 取得证书条件
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        private ParameterValues<int> GetTypeFlags(Dictionary<string, string> dict)
        {
            string typeFlags = string.Empty;
            int code = -1;
            var relation = LogicEnum.And;
            var list = new List<ParameterValue<int>>();
            var queryCondition = new ParameterValues<int>();
            if (dict.ContainsKey("TypeFlags"))
            {
                //页面条件中选择证书
                typeFlags = dict["TypeFlags"];
                int.TryParse(typeFlags, out code);
                var area = new ParameterValue<int>() { O = OptEnum.Equal, V = code };
                list.Add(area);
                queryCondition = new ParameterValues<int>()
                {
                    Logic = relation,
                    Values = list
                };
            }  
            //没有证书url参数
            if (string.IsNullOrEmpty(hdEmpItemType.Value.Trim()))
            {              
                return queryCondition;
            }
            string itemFlag=hdEmpItemFlag.Value.Trim();
            var arrt = hdEmpItemType.Value.Trim().Split(',');
            if (!string.IsNullOrEmpty(typeFlags))
            {
                //选择的证书包含在url参数传递的中
                if (arrt.Contains(typeFlags))
                {
                    if (itemFlag == "0")//只取选择的项
                    {
                        arrt = null;
                    }
                }
                else
                {
                    if (itemFlag == "1")//不包含在url中取选择项
                    {
                        arrt = null;
                    }
                }               
            }
            //加载url传递参数中的证书条件与选择的条件合并
            if (arrt != null && arrt.Length > 0)
            {
                foreach (var a in arrt)
                {
                    if (int.TryParse(a.Trim(), out code))
                    {
                        var area1 = new ParameterValue<int>() { O = OptEnum.Equal, V = code };
                        list.Add(area1);
                    }
                }
            }
            //人会生成的条件
            queryCondition = new ParameterValues<int>()
            {
                Logic = relation,
                Values = list
            };
            return queryCondition;
        }
        /// <summary>
        /// 返回查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnSearch_Click(object sender, EventArgs e)
        {
            string searchStr = Server.HtmlEncode(GetQueryConditions());
            hdReturnSearch.Value = searchStr;
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "closewin", "<script>returnToParent(1);</script>");
        }

       
    }
}